package com.tulele.vtool.task.schedule;

import com.tulele.vtool.model.ArticleInfo;
import com.tulele.vtool.model.combinedEntity.CombinedArticleInfoByArticleBrand;
import com.tulele.vtool.service.IArticleInfoService;
import com.tulele.vtool.utils.DateUtil;
import com.tulele.vtool.utils.RedisCacheUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Log4j2
public class BrandArticleRedisScheduleTask {

    @Autowired
    private IArticleInfoService articleInfoService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Scheduled(cron="0 0/3 * * * ?")
    public void processAddArticleToRedis() {

        List<CombinedArticleInfoByArticleBrand> articleInfos = articleInfoService.getToBeAddRedisArticleInfoOfBrand();

        if (CollectionUtils.isNotEmpty(articleInfos)) {

            articleInfos.stream().forEach(info -> {

                String articleBrandIdKey = "platformBrandArticle" + info.getArticleBrandId();
                Long result = redisCacheUtil.addEleToSet(articleBrandIdKey, info);

                log.info("[AddEleCountIn "+ articleBrandIdKey + "] = " + result);

                if (result.intValue() >= 0) {

                    ArticleInfo articleInfo = new ArticleInfo();
                    articleInfo.setId(info.getArticleId());
                    articleInfo.setRedisStoreStatus(1);
                    articleInfo.setModifyTime(DateUtil.getCurDate());
                    articleInfoService.modifyUserArticleInfo(articleInfo);

                }

            });

        }
    }

    @Scheduled(cron="0 0/15 * * * ?")
    public void processRemoveArticleToRedis() {

        List<CombinedArticleInfoByArticleBrand> articleInfos = articleInfoService.getToBeRemoveRedisArticleInfoOfBrand();

        if (CollectionUtils.isNotEmpty(articleInfos)) {

            articleInfos.stream().forEach(info -> {

                String articleBrandIdKey = "platformBrandArticle" + info.getArticleBrandId();
                boolean result = redisCacheUtil.removeEleInSet(articleBrandIdKey, info);

                log.info("[RemoveEleCountIn "+ articleBrandIdKey + "] = " + result);

                if (result) {

                    ArticleInfo articleInfo = new ArticleInfo();
                    articleInfo.setId(info.getArticleId());
                    articleInfo.setRedisStoreStatus(3);
                    articleInfo.setModifyTime(DateUtil.getCurDate());
                    articleInfoService.modifyUserArticleInfo(articleInfo);

                }

            });

        }
    }

}
